package com.ruoyi.web.controller.cs;

import java.util.*;
import java.util.stream.Collectors;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.CheckSwitch;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BasicsController;
import com.ruoyi.common.core.domain.Response;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.ResponsePageInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.cs.domain.*;
import com.ruoyi.cs.domain.dto.battle.BattleBaseResp;
import com.ruoyi.cs.domain.dto.battle.BattleInfoResp;
import com.ruoyi.cs.domain.dto.battle.BattleStartReq;
import com.ruoyi.cs.domain.vo.*;
import com.ruoyi.cs.service.*;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import com.ruoyi.system.mapper.SysDictDataMapper;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 盲盒对战信息Controller
 * 
 * @author ruoyi
 * @date 2021-08-05
 */
@Api(tags = {"盲盒对战信息"})
@RestController
@RequestMapping("/cs/battleinfo")
@SuppressWarnings("all")
public class TBattleInfoController extends BasicsController
{
    private static final Logger log = LoggerFactory.getLogger(TBattleInfoController.class);
    @Autowired
    private ITBattleInfoService tBattleInfoService;
    @Autowired
    private ITUserService itUserService;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private ITGoodsService tGoodsService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ITBattleUserService tBattleUserService;
    @Autowired
    private ITBoxService itBoxService;

    @Autowired
    private SysConfigMapper sysConfigMapper;


    /**
     * 查询盲盒对战信息列表
     */
    @ApiOperation("后台查询盲盒对战信息列表")
    @PreAuthorize("@ss.hasPermi('cs:battleinfo:list')")
    @PostMapping("/list")
    public ResponsePageInfo<TBattleBackVo> list(@RequestBody  TBattleBackVo vo)
    {
        startPage(vo.getPageNum(), vo.getPageSize());
        List<TBattleInfo> list = tBattleInfoService.battleBackList(vo);

        ResponsePageInfo rspData = new ResponsePageInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setTotal(new PageInfo(list).getTotal());
        List<TBattleBackVo> re = tBattleInfoService.selectTBattleInfoList(list);
        rspData.setRows(re);
        return rspData;
    }

    /**获取前端展示对战、禁止主播参加的字段值*/
    @ApiOperation("获取前端展示对战、禁止主播参加的字段值")
    @GetMapping(value = "/getValue")
    @ApiImplicitParam(name = "type",value = "类型 0-前端展示盲盒对战 1-禁止主播参与对战 2-是否允许会员参与官方对战" ,dataType = "String", paramType = "query", required = false)
    public Response<String> getValue(String type)
    {
        if (StringUtils.isEmpty(type)){
            return Response.fail(Constants.FAILCODE,"选择的参数类型不能为空!");
        }
        String value = null;
        if ("0".equals(type)){
            SysDictData ss  = sysDictDataMapper.selectDictDataById(190L);
            value = ss.getDictValue();
        }else if ("1".equals(type)){
            SysDictData ss  = sysDictDataMapper.selectDictDataById(191L);
            value = ss.getDictValue();
        }else {
            SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique("members_participate_in_official_battle");
            value = sysConfig.getConfigValue();
        }
        return Response.success(value);
    }
    /**设置前端展示对战、禁止主播参加的字段值*/
    @ApiOperation("设置前端展示对战、禁止主播参加的字段值")
    @PreAuthorize("@ss.hasPermi('cs:battleinfo:setValue')")
    @GetMapping(value = "/setValue")
    @Log(title = "设置前端展示对战、禁止主播参加的字段值", businessType = BusinessType.UPDATE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type",value = "类型 0-前端展示盲盒对战 1-禁止主播参与对战 2-是否允许会员参与官方对战" ,dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "value",value = "是否" , dataType = "String", paramType = "query", required = false),
    })
    public Response setValue(String type,String value)
    {
        if (StringUtils.isEmpty(type) || StringUtils.isEmpty(value)){
            return Response.fail(Constants.FAILCODE,"选择的参数类型不能和值都不能为空!");
        }
        if ("0".equals(type)){
            sysDictDataMapper.updateValue(value,"190");
        }else if ("1".equals(type)){
            sysDictDataMapper.updateValue(value,"191");
        }else if("2".equals(type)){
            SysConfig sysConfig = new SysConfig();
            sysConfig.setConfigId(129L);
            sysConfig.setConfigKey("members_participate_in_official_battle");
            sysConfig.setConfigValue(value);
            sysConfigMapper.updateConfig(sysConfig);
        }
        return Response.success();
    }
    /**盲盒对战收益统计*/
    @ApiOperation("盲盒对战收益统计")
    @PreAuthorize("@ss.hasPermi('cs:battleinfo:count')")
    @GetMapping(value = "/count")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime",value = "开始时间" ,dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "endTime",value = "结束时间" , dataType = "String", paramType = "query", required = false),
    })
    public Response<Map> count(String startTime, String endTime)
    {
        return tBattleInfoService.count(startTime, endTime);
    }

    /**
     * 盲盒对战箱子统计列表
     * @param tBattleBoxCountVo
     * @return
     */
    @ApiOperation("盲盒对战箱子统计列表")
    @PreAuthorize("@ss.hasPermi('cs:battleinfo:boxCountList')")
    @PostMapping(value = "/boxCountList")
    public ResponsePageInfo<Map> boxCountList(@RequestBody  TBattleBoxCountVo tBattleBoxCountVo)
    {
        List<Map> list = tBattleInfoService.boxCountList(tBattleBoxCountVo);
        return toResponsePageInfo(list);
    }


    /**
     * 保底饰品列表
     */
    @PreAuthorize("@ss.hasPermi('cs:battleinfo:floorsListBack')")
    @ApiOperation("保底饰品列表")
    @RequestMapping(name="保底饰品列表",value="floorsListBack",method = RequestMethod.POST)
    public ResponsePageInfo<TGoods> floorsListBack(@RequestBody TGoods tGoods)
    {
        startPage(tGoods.getPageNum(), tGoods.getPageSize());
        tGoods.setBackStage(Constants.BACKSTAGE);
        tGoods.setGoodsBelongingType(Constants.GOOGSBLTYPE6);
        List<TGoods> list = tGoodsService.floorsGoodsListBack(tGoods);
        return toResponsePageInfo(list);
    }


    /**
     * 保底饰品添加
     */
    @PreAuthorize("@ss.hasPermi('cs:battleinfo:floorsTGoodsAdd')")
    @ApiOperation("保底饰品添加")
    @RequestMapping(name="保底饰品添加",value="floorsTGoodsAdd",method = RequestMethod.POST)
    @Log(title = "对战保底饰品添加", businessType = BusinessType.INSERT)
    public Response floorsTGoodsAdd(@RequestBody TGoods tGoods)
    {
        return tGoodsService.floorsTGoodsBattleAdd(tGoods);
    }

    /**
     * 保底饰品编辑
     */
    @PreAuthorize("@ss.hasPermi('cs:battleinfo:floorsTGoodsEdit')")
    @ApiOperation("保底饰品编辑")
    @RequestMapping(name="保底饰品编辑",value="floorsTGoodsEdit",method = RequestMethod.POST)
    @Log(title = "对战保底饰品编辑", businessType = BusinessType.UPDATE)
    public Response floorsTGoodsEdit(@RequestBody TGoods tGoods)
    {
        return tGoodsService.floorsTGoodsEditBattle(tGoods);
    }

    /**
     * 默认保底饰品查询
     */
    @ApiOperation("默认保底饰品查询")
    @PreAuthorize("@ss.hasPermi('cs:battleinfo:defaultTGoods')")
    @RequestMapping(name="默认保底饰品查询",value="defaultTGoods",method = RequestMethod.GET)
    public Response<String> defaultTGoods()
    {
        SysDictData ss = sysDictDataMapper.selectDictDataById(200L);
        return Response.success(ss.getDictValue());
    }

    /**
     * 默认保底饰品编辑
     */
    @ApiOperation("默认保底饰品编辑")
    @PreAuthorize("@ss.hasPermi('cs:battleinfo:defaultTGoodsSet')")
    @RequestMapping(name="默认保底饰品编辑",value="defaultTGoodsSet",method = RequestMethod.GET)
    @Log(title = "对战默认保底饰品编辑", businessType = BusinessType.UPDATE)
    @ApiImplicitParam(name = "value",value = "饰品id" ,dataType = "String", paramType = "query", required = false)
    public Response<Integer> defaultTGoodsSet(String value)
    {
        String listClass = tGoodsService.defaultTGoodsSetBattle(value);
        int row = sysDictDataMapper.updateDefualtValue(value,"200",listClass);
        return toResponse(row);
    }


    /*-------------------------------------------------------前台---------------------------------------------------*/
    @ApiOperation("web前台查询盲盒对战信息列表")
    @PostMapping("/boxList")
    public ResponsePageInfo<TBox> boxList(@RequestBody PageInfoParamVo pageInfoParamVo)
    {
        startPage(pageInfoParamVo.getPageNum(),pageInfoParamVo.getPageSize());
        List<TBox> list = itBoxService.getBattleBoxList(Constants.BOXTYPE1,pageInfoParamVo.getBoxTitleId(),pageInfoParamVo.getSort());
        ResponsePageInfo<TBox> responsePageInfo= toResponsePageInfo(list);
        List<TBox> tBoxList = responsePageInfo.getRows();
        /*去重*/
        if (tBoxList.size() > 0) {
            tBoxList = tBoxList.stream().collect(
                    Collectors.collectingAndThen(
                            Collectors.toCollection(
                                    () -> new TreeSet<>(Comparator.comparing(box -> box.getBoxId()))
                            ),
                            ArrayList::new
                    )
            );
        }
        if(tBoxList.size()>0){
            if(StringUtils.isEmpty(pageInfoParamVo.getSort())){
                /**排序字段排序*/
                tBoxList = tBoxList.stream().sorted(Comparator.comparing(TBox::getSort)).collect(Collectors.toList());
            }else if ("0".equals(pageInfoParamVo.getSort())){
                /**价格顺序*/
                tBoxList = tBoxList.stream().sorted(Comparator.comparing(TBox::getBoxPrice)).collect(Collectors.toList());
            }else {
                /**价格倒序*/
                tBoxList = tBoxList.stream().sorted(Comparator.comparing(TBox::getBoxPrice,Comparator.reverseOrder())).collect(Collectors.toList());
            }
        }
        responsePageInfo.setRows(tBoxList);

        return responsePageInfo;
    }

    @CheckSwitch
    @ApiOperation("web创建对战")
    @PostMapping("/createBattle")
    @Log(title = "创建对战", businessType = BusinessType.INSERT)
    public Response<Map> createBattle(@Validated  @RequestBody TbattleCreateVo tbattleCreateVo)
    {
        try {
            String userId = tokenService.getLoginUserId();
            return tBattleInfoService.createBattle(userId,tbattleCreateVo);
        } catch (Exception e) {
            log.error("创建盲盒对战失败:{}",e);
            return Response.fail(Constants.FAILCODE,"系统繁忙，请联系管理员处理！");
        }
    }


    @ApiOperation("web对战房间列表")
    @GetMapping("/battleList")
    @Cacheable(value="twoSecondsCache", condition = "#battleListType == '0' and #pageNum == 1 and #pageSize == 10",unless = "#result == null", key = "{'battleList',#battleListType, #pageNum,#pageSize}")
    public ResponsePageInfo<BattleBaseResp> battleList(@RequestParam(value = "battleListType",defaultValue = "0") String battleListType,
                                                       @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                                                       @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize)
    {
        startPage(pageNum,pageSize);
        List<BattleBaseResp> list = tBattleInfoService.battleListV2(battleListType,tokenService.getLoginUserId());
        return toResponsePageInfo(list);
    }

    @CheckSwitch
    @ApiOperation("参与对战")
    @PutMapping("/startBattle")
    @Log(title = "参与对战", businessType = BusinessType.UPDATE)
    public Response<Map> startBattle(@Validated @RequestBody BattleStartReq req)
    {
        try {
            return tBattleInfoService.startBattleV2(req,tokenService.getLoginUserId());
        } catch (Exception e) {
            log.error("立即加入对战房间异常:{}", e);
            return Response.fail(Constants.FAILCODE, "系统繁忙，请联系管理员处理！");
        }
    }

    @ApiOperation("对战详情")
    @GetMapping("/battleInfo/{battleId}")
    public Response<BattleInfoResp> battleInfo(@PathVariable("battleId") String battleId)
    {
        try {
            return tBattleInfoService.battleInfoV2(battleId,tokenService.getLoginUserId());
        } catch (Exception e) {
            log.error("获取对战详情失败:{}",e);
            return Response.fail(Constants.FAILCODE,"系统繁忙，请联系管理员处理！");
        }
    }

    @ApiOperation("机器人对战统计")
    @GetMapping("/robatBattleInfoList")
    public Response<List<TUserRobotBattleInfoVo>> robatBattleInfoList(){
        List<TUserRobotBattleInfoVo> tUserRobotBattleInfoVos = tBattleUserService.robatBattleInfoList();
        return Response.success(tUserRobotBattleInfoVos);
    }

    @ApiOperation("对战排名")
    @GetMapping("/battleRanking")
    @ApiImplicitParam(name = "type",value = "类型 today 今日 yesterday 昨日" ,dataType = "String", paramType = "query", required = true)
    @Cacheable(value="oneSecondCache", key="'battleRanking'+#p0")
    public Response<Map> battleRanking(String type){
        LoginUser loginUser = tokenService.getLoginUserWeb(ServletUtils.getRequest());
        String userId = null;
        if(loginUser != null){
            SysUser sysUser = loginUser.getUser();
            userId = sysUser.getLoginUserId();
        }
        Map map = tBattleUserService.battleRanking(type,userId);
        return Response.success(map);
    }

}
